﻿Imports System.Data.OleDb
Public Class addCar
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub btn_Save_Click(sender As Object, e As EventArgs) Handles btn_Save.Click

        Dim newFileName As String
        newFileName = Guid.NewGuid().ToString() & getSuffix(fu_Picture.FileName)

        If fu_Picture.HasFile Then
            fu_Picture.SaveAs(Server.MapPath("Pictures") & "/" & newFileName)
        End If

        Dim sql As String = "INSERT INTO Car (Manufacturer,Model,Website,Contact,Picture,PostCode,SafetyRating) VALUES (@f1,@f2,@f3,@f4,@f5,@f6,@f7)"
        Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("CarsConnectionString").ConnectionString)
        Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)

        cmd.Parameters.AddWithValue("@f1", tb_Manufacturer.Text)
        cmd.Parameters.AddWithValue("@f2", tb_Model.Text)
        cmd.Parameters.AddWithValue("@f3", tb_Website.Text)
        cmd.Parameters.AddWithValue("@f4", tb_Contact.Text)
        cmd.Parameters.AddWithValue("@f5", "Pictures/" & newFileName)
        cmd.Parameters.AddWithValue("@f6", tb_PostCode.Text)
        cmd.Parameters.AddWithValue("@f7", rbl_SafeyRating.SelectedValue)

        conn.Open()
        cmd.ExecuteNonQuery()
        conn.Close()
        cmd.Dispose()
        conn.Dispose()

        Response.Redirect("Default.aspx")

    End Sub

    Function getSuffix(ByVal fn As String)
        Dim fileParts = fn.Split(".")
        Dim suffix = fileParts(fileParts.Length - 1)
        Return "." & suffix
    End Function

End Class